extends Node

# 允许我们选择要实例化的 Mob 场景
var mob_scene=preload("res://tscn/plant.tscn")

#是否跟随移动，用于种植植物时
var plant_follow = false

#单个格子的宽和高
var grid_width = 109
var grid_height = 130

#左上角第一个植物的横纵坐标偏移
var start_pos = Vector2(210, 123)

#当前要种植的植物
var current_plant: String

# Called when the node enters the scene tree for the first time.
func _ready():
	$CardList.set_sun_point(500)
	$cursor_plant.visible = false
	$shadow_plant.visible = false
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	var direction = Vector2(-1, 0)
	$zombie.position += direction*delta*$zombie.speed
	pass

func _input(event):
	if plant_follow and event is InputEventMouseButton:
		if event.pressed and event.button_index==2: #右键按下，撤销种植操作
			plant_follow = false
			$cursor_plant.visible = false
			$shadow_plant.visible = false
		if event.pressed and event.button_index==1: #左键按下，种植植物
			plant_a_plant(event.position)
			plant_follow = false
			$cursor_plant.visible = false
			$shadow_plant.visible = false
	if plant_follow and event is InputEventMouseMotion: #鼠标在视口里移动即可触发
		#print(event.position)
		var logic_p = mouse_pos_to_logic_pos(event.position)
		if logic_p.x>=0 and logic_p.x<9 and logic_p.y>=0 and logic_p.y<5:
			#绘制阴影植物
			$shadow_plant.position = get_plant_pos(logic_p)
			$shadow_plant.visible = true
		else: #在范围外面的不绘制
			$shadow_plant.visible = false
		#先移动到位，再显现出来
		$cursor_plant.position = event.position - $cursor_plant.size/2
		if $cursor_plant.visible == false:
			$cursor_plant.visible = true
	pass

#当选择一种植物种植时
func _on_card_list_plant_select(str: String):
	current_plant = str
	print(str)
	var texture = ImageTexture.create_from_image(
		Image.load_from_file("res://images/represent/"+str+".png"))
	$cursor_plant.texture = texture
	$shadow_plant.texture = texture
	plant_follow = true
	pass # Replace with function body.

#将鼠标的坐标转化为格子的坐标
func mouse_pos_to_logic_pos(pos: Vector2):
	var delta_p = pos-start_pos
	var logic_p = Vector2.ZERO
	@warning_ignore("integer_division")
	logic_p.x = int(delta_p.x)/grid_width
	@warning_ignore("integer_division")
	logic_p.y = int(delta_p.y)/grid_height
	return logic_p

#通过逻辑坐标获取植物位置
func get_plant_pos(logic_p: Vector2):
	logic_p.x *= grid_width
	logic_p.y *= grid_height
	return start_pos + logic_p

#种植一棵植物
func plant_a_plant(position: Vector2):
	#只有有阴影的情况下种植植物才成立
	if $shadow_plant.visible == true:
		var new_plant = mob_scene.instantiate()
		new_plant.set_plant(current_plant)
		var logic_p = mouse_pos_to_logic_pos(position)
		new_plant.position = get_plant_pos(logic_p)
		add_child(new_plant)
